#include "stdafx2.h"
#include "log.h"

bmtp_fd_t bmtp_log_file_open(const char *name) {
#ifdef WIN32
    return CreateFile(name, GENERIC_READ | FILE_APPEND_DATA, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
#else
    return open(name, O_RDWR | O_APPEND | O_CREAT | O_CLOEXEC, 0777);
#endif
}

ssize_t bmtp_log_file_append(bmtp_fd_t fd, const void *buf, size_t count) {
#ifdef WIN32
	u_long nwrite;
	if (WriteFile(fd, buf, count, &nwrite, NULL) == 0) {
		return -1;
	}

	return nwrite;
#else
    return write(fd, buf, count);
#endif
}

int bmtp_log_init( struct bmtp_context *bmtp ) {
    if( bmtp->log_buf == NULL ) {
        bmtp->log_buf_len = 1024;
        bmtp->log_buf = (char *)malloc( bmtp->log_buf_len );
        if( bmtp->log_buf == NULL ) {
            // 内存不足
            return 1;
        }
    }
    
    char log_file[128];
    snprintf(log_file, sizeof(log_file) - 1, "./bmtp_%s_%d.log",
        inet_ntoa(bmtp->server_addr.sin_addr),
        ntohs(bmtp->server_addr.sin_port));

	bmtp->log_fd = bmtp_log_file_open( log_file );
    if( bmtp->log_fd <=0 ) {
		// 无法创建或打开日志文件
        return 1;
    }
    
    return 0;
}

int bmtp_log_add( struct bmtp_context *bmtp, const char *fmt, ... ) {
    va_list args;

    va_start(args, fmt);
    int len = (size_t) vsnprintf(bmtp->log_buf, bmtp->log_buf_len, fmt, args);
    va_end(args);

	//bmtp_log_file_append(bmtp->log_fd, wbt_time_str_log.str, wbt_time_str_log.len);
	bmtp_log_file_append(bmtp->log_fd, bmtp->log_buf, len);
    
    return 0;
}

int bmtp_log_print( struct bmtp_context *bmtp, const char *fmt, ... ) {
    va_list args;

    va_start(args, fmt);
    int len = (size_t) vsnprintf(bmtp->log_buf, bmtp->log_buf_len, fmt, args);
    va_end(args);

    fprintf(stdout, "%.*s", len, bmtp->log_buf);
    
    return 0;
}

